/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lab2cyclebuffer;

/**
 *
 * @author Daryna_Ragimova
 */
public class Buffer {

    private int[] buf;
    private int size;
    private boolean empty = true;
    private boolean full = false;
    private int start = 0;
    private int end = -1;

    public Buffer(int N) {
        buf = new int[N];
        this.size = N;
    }

    
    public synchronized void put(Integer i) throws InterruptedException {
        while (full) {
            if (start == (end + 1) % size) {
                System.out.println("Try to put " + i);
                wait();
            }
        }
        end = (end + 1) % size;
        System.out.println("Put " + i);
        buf[end] = i;
        empty = false;
        if ((end + 1) % size == start) {
            full = true;
        }
        notifyAll();
    }

    public synchronized Integer get() throws InterruptedException {
        while (empty) {
            if (start == (end + 1) % size) {
                System.out.println("Try to get ");
                wait();
            }
        }
        int t = buf[start];
        buf[start] = 0;
        start = (start + 1) % size;
        full = false;
        if ((end + 1) % size == start) {
            empty = true;
        }
        notifyAll();
        return t;
    }
}
